<script lang="ts">
import { FButton, useFormLayoutContext } from 'fok-ui';
import { PropType, defineComponent, h, watch } from 'vue';

export default defineComponent({
  name: 'f-dy-operates',
  props: {
    fields: Array as PropType<string[]>,
    rowId: [String, Number] as PropType<string | number>
  },
  setup: (props) => {
    const context = useFormLayoutContext();

    const firstValue = context.model.value[props.fields![0]];
    const currentValue = context.model.value[props.fields![props.fields!.length - 1]];
    console.log(firstValue, currentValue);
    // 根据第一列的数据长度进行按钮长度初始化，保证按钮数量与数据长度一致
    if (firstValue && firstValue.length !== currentValue?.length) {
      context.model.value[props.fields![props.fields!.length - 1]] = firstValue.map((item) => ({
        key: item.key,
        value: ''
      }));
    }

    const add = () => {
      // 确保行上的唯一key再所有的列中都一样，方便查询
      const key = Math.random().toString().slice(2);
      props.fields?.forEach((item) => {
        if (!context.model.value[item]) context.model.value[item] = [];
        const insertIndex = context.model.value[item].findIndex((obj) => obj.key === props.rowId);
        const copyData = context.model.value[item].slice();
        copyData.splice(insertIndex + 1, 0, {
          key: key,
          value: ''
        });
        // 确保是新数据，而不是直接修改引用
        context.model.value[item] = copyData;
      });
    };

    const remove = () => {
      props.fields?.forEach((item) => {
        if (context.model.value[item]) {
          const copyData = context.model.value[item].slice();
          copyData.splice(
            context.model.value[item].findIndex((obj) => obj.key === props.rowId),
            1
          );
          // 确保是新数据，而不是直接修改引用
          context.model.value[item] = copyData;
        }
      });
    };
    return () =>
      h('div', [
        h(FButton, { shape: 'circle', size: 'small', onClick: () => add() }, () => '+'),
        h(
          FButton,
          { class: 'ml6', shape: 'circle', size: 'small', onClick: () => remove() },
          () => '-'
        )
      ]);
  }
});
</script>
